package com.inspur.edp.common.expr.visitor.field;


import com.inspur.edp.common.expr.ast.ASTContext;
import com.inspur.edp.common.expr.ast.CompileUnitParser;
import com.inspur.edp.common.expr.ast.CompileUnitVisitor;
import com.inspur.edp.common.expr.spi.FieldVisitor;
import com.inspur.edp.common.expr.visitor.VisitResult;
import com.inspur.edp.common.type.Field;


/**
 * @author lizhaorui
 * @description TODO
 * @date 2024/7/16 8:43
 */
public class PublicFieldVisitor implements FieldVisitor {

    public static final String KIND = "default";

    @Override
    public String getKind() {
        return KIND;
    }

    @Override
    public VisitResult visitGetter(CompileUnitVisitor visitor,
                                   ASTContext context,
                                   CompileUnitParser.FieldAccessExprContext fieldAccessExprContext,
                                   CompileUnitParser.ExpressContext objectExpr, Field field) {
        String objectExprDsl = visitor.visitExpress(objectExpr).toString();
        Object tagValue = objectExpr.getTag(FieldVisitor.CLASS_CAST_TAG_KEY);
        if (tagValue != null) {
            objectExprDsl = "(" + objectExprDsl + ")";
        }
        return new VisitResult(String.format("%s.%s", objectExprDsl, field.getCode()));
    }

    @Override
    public VisitResult visitSetter(CompileUnitVisitor visitor, ASTContext context, CompileUnitParser.ExpressContext objectExpr, Field field, CompileUnitParser.ExpressContext valueExpr) {
        String objectExprDsl = visitor.visitExpress(objectExpr).toString();
        Object tagValue = objectExpr.getTag(FieldVisitor.CLASS_CAST_TAG_KEY);
        if (tagValue != null) {
            objectExprDsl = "(" + objectExprDsl + ")";
        }
        String valueExprDsl = visitor.visitExpress(valueExpr).toString();
        return new VisitResult(String.format("%s.%s = %s", objectExprDsl, field.getCode(), valueExprDsl));
    }


}
